package com.cjf.androidstudy.component.fragment;

import androidx.annotation.IdRes;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.cjf.androidstudy.R;

public class FragmentActivity extends AppCompatActivity {

    private Button leftFragmentButton1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment);

        // 动态布局，定义FragmentLayout，然后用Fragment来替换内容
        replaceFragment(R.id.rightFragmentLayOut, new RightFragment());
        leftFragmentButton1 = findViewById(R.id.leftFragmentButton1);
        leftFragmentButton1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Fragment rightFragmentLayOut = getSupportFragmentManager().findFragmentById(R.id.rightFragmentLayOut);
                if (rightFragmentLayOut instanceof RightFragment) {
                    replaceFragment(R.id.rightFragmentLayOut, new AnotherRightFragment());
                } else {
                    replaceFragment(R.id.rightFragmentLayOut, new RightFragment());
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * 替换
     *
     * @param fragment
     */
    private void replaceFragment(@IdRes int containerViewId, Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(containerViewId, fragment);
        // 这一行代码用于控制碎片的返回栈
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }
}
